package com.blockchain.console.service.system.achieve;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.blockchain.common.enums.LoginStatus;
import com.blockchain.console.config.ConsoleConst;
import com.blockchain.console.service.system.UserLoginLogManage;
import com.blockchain.console.service.system.entity.UserLog;
import com.blockchain.console.service.system.query.UserLogQuery;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.framework.service.query.Paging;
import com.blockchain.framework.service.query.PagingResult;
import com.blockchain.util.StringHelper;
import com.blockchain.util.parser.EnumParser;

public class UserLoginLogManageImpl extends AbstractSystemService implements
		UserLoginLogManage {

	public static class UserLoginLogManageFactory implements
			ServiceFactory<UserLoginLogManage> {

		@Override
		public UserLoginLogManage newInstance(ServiceResource serviceResource) {
			return new UserLoginLogManageImpl(serviceResource);
		}
	}

	public UserLoginLogManageImpl(ServiceResource serviceResource) {
		super(serviceResource);
	}

	@Override
	public PagingResult<UserLog> seacrch(UserLogQuery query, Paging paging)
			throws Throwable {
		String sql = "SELECT F01,F02,F03,F04,F05,F06 FROM T6051 WHERE 1=1";
		StringBuilder sb = new StringBuilder();
		sb.append(sql);
		List<Object> parameters = new ArrayList<>();
		if (query != null) {
			String accountName = query.getAccountName();
			Timestamp createTimeStart = query.getCreateTimeStart();
			Timestamp createTimeEnd = query.getCreateTimeEnd();
			if (!StringHelper.isEmpty(accountName)) {
				sb.append(" AND F02 LIKE ?");
				parameters.add(getSQLConnectionProvider().allMatch(accountName));
			}
			if (createTimeStart != null) {
				sb.append(" AND DATE(F03)>=?");
				parameters.add(createTimeStart);
			}
			if (createTimeEnd != null) {
				sb.append(" AND DATE(F03)<=?");
				parameters.add(createTimeEnd);
			}
		}
		sb.append(" ORDER BY F03 DESC");
		return selectPaging(getConnection(ConsoleConst.DB_USER),
				new ArrayParser<UserLog>() {

					@Override
					public UserLog[] parse(ResultSet resultSet)
							throws SQLException {
						List<UserLog> lists = new ArrayList<>();
						while (resultSet.next()) {
							UserLog userLog = new UserLog();
							userLog.id = resultSet.getInt(1);
							userLog.accountName = resultSet.getString(2);
							userLog.lastLoginTime = resultSet.getTimestamp(3);
							userLog.lastIp = resultSet.getString(4);
							userLog.isSuccess = EnumParser.parse(
									LoginStatus.class, resultSet.getString(5));
							userLog.shuDi = resultSet.getString(6);
							lists.add(userLog);
						}
						return lists.toArray(new UserLog[lists.size()]);
					}
				}, paging, sb.toString(), parameters);
	}
}
